package dao

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"log"
)

const (
	driverName = "mysql"
	//dataSourceName = "root:root@tcp(8.140.22.220:3306)/sql_test"
	dataSourceName = "root:root@tcp(localhost:3306)/sql_test"
	maxOpenCons    = 100
	maxIdleCons    = 20
)

var client *sql.DB

// 易错点: 匿名导入驱动包, 注册驱动, database/sql -> init

func init() {
	var err error
	client, err = sql.Open(driverName, dataSourceName)
	if err != nil {
		log.Fatalln(err)
	}
	err = client.Ping()
	if err != nil {
		log.Fatalln(err)
	}

	client.SetMaxOpenConns(maxOpenCons)
	client.SetMaxIdleConns(maxIdleCons)
}

var clientSqlx *sqlx.DB

func init() {
	dsn := "root:root@tcp(localhost:3306)/sql_test?charset=utf8mb4&parseTime=True"
	// 也可以使用MustConnect连接不成功就panic
	// clientSqlx, err = sqlx.Connect("mysql", dsn)
	clientSqlx = sqlx.MustConnect("mysql", dsn)

	clientSqlx.SetMaxOpenConns(20)
	clientSqlx.SetMaxIdleConns(10)
}

func Close() error {
	return client.Close()
}

func CloseSqlx() error {
	return clientSqlx.Close()
}
